package com.ruoyi.client.service.impl;

import com.ruoyi.client.mapper.ClientUserMapper;
import com.ruoyi.client.pojo.form.UserLoginForm;
import com.ruoyi.client.pojo.form.UserRegisterForm;
import com.ruoyi.client.pojo.vo.UserVo;
import com.ruoyi.client.service.IClientUserService;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.common.utils.sign.Md5Utils;
import com.ruoyi.xz.domain.User;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class ClientUserServiceImpl implements IClientUserService {
    @Resource
    private ClientUserMapper clientUserMapper;

    @Override
    public UserVo login(UserLoginForm form) {
        //判断用户是否存在
        User user = clientUserMapper.selectByName(form.getName());
        if (user == null) {
            throw new ServiceException("用户名不存在或密码错误");
        }

        String passwordMd5 = Md5Utils.hash(form.getPassword() + user.getSalt());
        if(passwordMd5.equals(user.getPassword())){
            UserVo userVo = new UserVo();
            BeanUtils.copyProperties(user,userVo);
            return userVo;
        }
        throw new ServiceException("用户登录错误");
    }

    @Override
    public UserVo register(UserRegisterForm form) {
        User user = clientUserMapper.selectByName(form.getName());
        if (user != null) {
            throw new ServiceException("用户名已存在");
        }
        user = new User();
        BeanUtils.copyProperties(form,user);
        // 密码加密处理
        String salt = Md5Utils.hash(String.valueOf(System.currentTimeMillis()));
        String passwordMd5 = Md5Utils.hash(form.getPassword() + salt);
        user.setSalt(salt);
        user.setPassword(passwordMd5);
        // 调用数据层,注册用户数据
        if (clientUserMapper.register(user)) {
            UserVo userVo = new UserVo();
            BeanUtils.copyProperties(user, userVo);
            return userVo;
        }
        return null;
    }

    @Override
    public UserVo selectById(Long id) {
        return clientUserMapper.selectById(id);
    }
}
